package com.rybbaby.tss.platform.filters;

import com.rybbaby.tss.core.web.controller.BaseController;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author 谢进伟
 * @description 登录过滤器
 * @createDate 2016年5月25日 上午9:33:49
 */
public class LoginFilter extends BaseController implements Filter {

    private Logger log = Logger.getLogger(LoginFilter.class);

    private List<String> excludePath;
    private List<String> notValidateLoginViews;

    @Override
    public void destroy() {
        log.info("登录过滤器已销毁!");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse rep, FilterChain fc) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        String contextPath = request.getContextPath();
        String requestURI = request.getRequestURI();
        if (requestURI.contains("?")) {
            requestURI = StringUtils.substringBefore(requestURI, "?");
        }
        if (StringUtils.isNotBlank(contextPath)) {
            requestURI = StringUtils.substringAfter(requestURI, contextPath);
        }
        requestURI = requestURI.replaceAll("//", "/");
        boolean doFilter = false;
        if (requestURI.equals("/switchView.do")) {
            String switchViewPath = request.getParameter("viewPath");
            if (StringUtils.isNotBlank(switchViewPath) && this.notValidateLoginViews.contains(switchViewPath.trim())) {
                doFilter = true;
            }
        }
        if (!"/".equals(requestURI) && !"".equals(requestURI)) {
            if (requestURI.startsWith("/assets/")) {// 静态资源
                doFilter = true;
            } else {
                if (!doFilter && excludePath != null) {
                    for (String uri : excludePath) {
                        if (requestURI.startsWith(uri.trim())) {
                            doFilter = true;
                            break;
                        }
                    }
                }
            }
        }
        if (!doFilter) {
            Object loginUser = getLoginUser(request);
            if (loginUser != null) {
                doFilter = true;
            }
        }
        if (doFilter) {
            fc.doFilter(req, rep);
        } else {
            HttpServletResponse response = (HttpServletResponse) rep;
            response.sendRedirect(contextPath + "/login/toLoginView.do?timer=" + System.currentTimeMillis());
        }
    }

    /**
     * 获取登录对象
     *
     * @param request
     * @return
     */
    private Object getLoginUser(HttpServletRequest request) {
        HttpSession session = request.getSession();
        Object loginUser = session.getAttribute("loginUser");
        return loginUser;
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        log.info("正在启用登录过滤器...");
        initExcludePath(config);
        initSwitchToSpecialViews(config);
    }

    private void initExcludePath(FilterConfig config) {
        // 初始化不需要过滤的请求
        String excludePathStr = config.getInitParameter("excludePath");
        if (StringUtils.isNotBlank(excludePathStr)) {
            excludePath = Arrays.asList(excludePathStr.split(","));
        }
    }

    private void initSwitchToSpecialViews(FilterConfig config) {
        // 初始化直接调用siwitch不需要验证登陆的特殊视图
        String notValidateLoginViewsStr = config.getInitParameter("notValidateLoginViews");
        if (StringUtils.isNotBlank(notValidateLoginViewsStr)) {
            List<String> asList = Arrays.asList(notValidateLoginViewsStr.split(","));
            if (notValidateLoginViews == null) {
                notValidateLoginViews = new ArrayList<String>();
            }
            for (String string : asList) {
                notValidateLoginViews.add(StringUtils.trim(string));
            }
        }
    }

}
